<template>
  <section class='f-msg-detail'>
    <div v-if="name == '供应商消息' || name == '订单消息'" class="f-mt-10 f-center" style="font-size: 12px;">
      <span v-if="name == '供应商消息'" class="f-mr-05" @click="openPicker('选择供应商')">{{supplierName || '全部供应商'}}</span>
      <span v-if="name == '订单消息'" class="f-mr-05" @click="openPicker('选择消息类型')">{{msgName || '全部类型'}}</span>
      <van-icon name="arrow-down" />
    </div>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" :style="{ height: currentHeight }" style="overflow-y: auto">
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <ul class="f-cell-ground" v-for="(item,index) in tableData" :key="index">
          <li class="f-cell">
            <p class="f-center" style="font-size: 13px;">{{ getDateTime(item.createTime)[6] }}</p>
            <div class="f-card f-mt-10">
              <p style="font-size: 13px;padding: 21px 15px">{{item.title}}</p>
              <p class="f-divider"></p>
              <div class="f-flex-between" style="padding: 9px 14px" @click="toRichText(item)">
                <p v-if="name == '供应商消息'" style="color: #666666;font-size: 12px;">来源：{{item.createShopName}}</p>
                <p v-else style="color: #666666;font-size: 12px;">类型：{{messageType[item.messageType]}}</p>
                <van-icon class="f-ml-05" name="arrow" />
              </div>

              <img v-if="item.readStatus == 0" class="f-weidu" src="@/assets/icons/jhh_message_weidu.png" alt="">
            </div>
          </li>
        </ul>
      </van-list>
    </van-pull-refresh>

    <van-popup v-model:show="showPicker" closeable position="bottom" close-icon-position="top-left">
      <p class="f-popup-title">{{pickerName}}</p>

      <van-picker ref="pickerRef" v-model="selectShopId" :columns="pickerName == '选择供应商'? mySupplierList: msgTypeList"
        :columns-field-names="pickerName == '选择供应商'? customFieldName: {}" :show-toolbar="false" />

      <div class="f-popup-btn">
        <van-button block type="primary" @click="handlePicker()">确定</van-button>
      </div>
    </van-popup>
  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import { getDateTime, setStore } from '@/utils/utils';
import api from './api'

export default {
  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const pickerRef = ref()

    const state = reactive({
      name: '',

      searchForm: {
        "endTime": "",
        "messageMode": route.query.type, // 0-我发布的消息,1-系统消息，2-商品消息，3-订单消息，4-来自供应商的消息(我的消息),5-发布的系统消息
        "messageType": "",
        "orderBy": "",
        "page": 1,
        "size": 10,
        "startTime": "",
        "supplierShopId": ""
      },

      loading: false,
      finished: false,
      refreshing: false,
      tableData: [],
      total: 0,

      currentHeight: '500px',

      messageType: {
        "10": "新商品上架",
        "11": "商品上架",
        "12": "商品下架",
        "13": "商品解冻",
        "14": "商品冻结",
        "20": "销售订单",
        "21": "生产订单",
        "23": "佣金订单",
        "24": "提现订单",
        "31": "系统全部消息",
        "32": "系统指定消息",
        "41": "号卡新商品上架",
      },

      showPicker: false,
      pickerName: "",
      selectShopId: [],

      supplierName: "",
      mySupplierList: [],
      customFieldName: {
        text: 'shopName',
        value: 'shopId',
        children: 'children'
      },

      msgName: "",
      msgTypeList: [
        { text: '全部类型', value: '' },
        { text: '重要消息', value: '1' },
        { text: '普通消息', value: '2' },
        { text: '新商品上架', value: '10' },
        { text: '商品上架', value: '11' },
        { text: '商品下架', value: '12' },
        { text: '商品解冻', value: '13' },
        { text: '商品冻结', value: '14' },
      ],
    })

    onMounted(() => {
      state.name = route.query.name

      store.commit("setNavBar", {
        title: state.name,
        show: true,
        left: true,
        leftType: 'back',
        right: false,
        rightText: '',
      });

      if (state.name == '供应商消息' || state.name == '订单消息') {
        state.currentHeight = window.innerHeight - 110 + 'px'
      } else {
        state.currentHeight = window.innerHeight - 80 + 'px'
      }

      getSupplierList()
    })

    const getSupplierList = () => {
      api.mySupplierList().then(res => {
        state.mySupplierList = res.data
        state.mySupplierList.unshift({
          shopName: '全部供应商',
          shopId: '',
        })
      })
    }

    const onLoad = () => {
      let json = JSON.parse(JSON.stringify(state.searchForm))

      if (state.refreshing) {
        state.tableData = [];
        state.refreshing = false;
      }

      api.messageSearch(json).then(res => {
        console.log(res.data.records)
        state.refreshing = false

        if (res.data.records.length) state.searchForm.page += 1
        state.tableData.push(...res.data.records)

        // 防止触发两次
        if (state.tableData.length >= res.data.total) {
          state.finished = true;
        } else {
          state.finished = false;
        }

        // 加载状态结束
        state.loading = false;

        // 数据全部加载完成
        if (state.tableData.length < 10) {
          state.finished = true;
        }
      }).catch(err => {
        state.loading = false;
        state.finished = true;
        state.refreshing = false
      })
    };

    const onRefresh = () => {
      state.searchForm.page = 1

      // 清空列表数据
      state.finished = false;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      state.loading = true;
      onLoad();
    };

    const openPicker = (e) => {
      state.pickerName = e
      state.showPicker = true
    }

    const handlePicker = () => {
      let data = pickerRef.value.confirm().selectedOptions[0]
      if (state.pickerName == '选择供应商') {
        state.supplierName = data.shopName
        state.searchForm.supplierShopId = data.shopId
        state.refreshing = true
        onRefresh()
      } else {
        state.msgName = data.text
        state.searchForm.messageType = data.value
        state.refreshing = true
        onRefresh()
      }
      state.showPicker = false
    }

    const toRichText = (params) => {
      setStore('Message_Content', { content: params.messageContent })
      router.push({
        path: "/msg/richText",
        query: {
          messageId: params.messageId,
          queryData: params.messageContent ? "{}" : JSON.stringify(params),
          name: state.name
        }
      })
    }

    return {
      ...toRefs(state),
      pickerRef,
      getDateTime,
      onLoad,
      onRefresh,
      openPicker,
      handlePicker,
      toRichText
    }
  }
}
</script>
<style lang='scss' scoped>
.f-msg-detail {
  .f-cell-ground {
    display: flex;
    justify-content: center;
    padding-top: 10px;
    .f-cell {
      margin-bottom: 21px;
      .f-card {
        width: 354px;
        background: #ffffff;
        border-radius: 10px;
        position: relative;
        .f-divider {
          margin: 0 5px;
          height: 1px;
          background: #aaaaaa;
        }
        .f-weidu {
          width: 28px;
          height: 28px;
          position: absolute;
          right: 0;
          top: 0;
        }
      }
    }
  }
}
</style>